package com.yys.apm.controller;

import com.yys.apm.common.exception.BusinessException;
import com.yys.apm.common.response.Response;
import com.yys.apm.common.utils.SignUtil;
import com.yys.apm.service.IDataReceiveService;
import com.yys.apm.utils.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 数据接收
 *
 * @author Yingsheng Ye
 */
@RestController
public class DataReceiverController {

    private static final Logger logger = LoggerFactory.getLogger(DataReceiverController.class);

    @Value("${secret-key}")
    private String secretKey;

    @PostMapping("/dataReceive")
    public Response<String> dataReceive(String data, String serviceCode, String timestamp, String sign) {
        try {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("data", data);
            dataMap.put("serviceCode", serviceCode);
            dataMap.put("timestamp", timestamp);
            if (null == sign || !sign.equals(SignUtil.sign(dataMap, secretKey))) {
                throw new BusinessException("签名验证错误");
            }
            if (null == timestamp || (System.currentTimeMillis() - Long.parseLong(timestamp)) > 3000) {
                throw new BusinessException("接口超时错误");
            }
            logger.info("接收数据:{}", data);
            IDataReceiveService dataReceiveService = SpringContextUtil.getBean(serviceCode, IDataReceiveService.class);
            //调用处理
            dataReceiveService.dataProcess(data);
        } catch (BusinessException e) {
            logger.error("数据处理异常:{}", e.getMessage(), e);
            return Response.failed(e.getMessage());
        }
        return Response.success();
    }

}
